package com.anji.plus.ajpushlibrary.xm;

import android.content.Context;
import android.text.TextUtils;

import com.anji.plus.ajpushlibrary.AppSpPushConfig;
import com.anji.plus.ajpushlibrary.AppSpPushLog;
import com.anji.plus.ajpushlibrary.AppSpPushConstant;
import com.anji.plus.ajpushlibrary.model.AppSpModel;
import com.anji.plus.ajpushlibrary.service.IAppSpCallback;
import com.anji.plus.ajpushlibrary.util.MessageUtil;
import com.anji.plus.ajpushlibrary.util.SPUtil;
import com.xiaomi.mipush.sdk.ErrorCode;
import com.xiaomi.mipush.sdk.MiPushClient;
import com.xiaomi.mipush.sdk.MiPushCommandMessage;
import com.xiaomi.mipush.sdk.MiPushMessage;
import com.xiaomi.mipush.sdk.PushMessageReceiver;

import org.json.JSONObject;

import java.util.List;

/**
 * 1、PushMessageReceiver 是个抽象类，该类继承了 BroadcastReceiver。<br/>
 * 2、需要将自定义的 DemoMessageReceiver 注册在 AndroidManifest.xml 文件中：
 * <pre>
 * {@code
 *  <receiver
 *      android:name="com.xiaomi.mipushdemo.DemoMessageReceiver"
 *      android:exported="true">
 *      <intent-filter>
 *          <action android:name="com.xiaomi.mipush.RECEIVE_MESSAGE" />
 *      </intent-filter>
 *      <intent-filter>
 *          <action android:name="com.xiaomi.mipush.MESSAGE_ARRIVED" />
 *      </intent-filter>
 *      <intent-filter>
 *          <action android:name="com.xiaomi.mipush.ERROR" />
 *      </intent-filter>
 *  </receiver>
 *  }</pre>
 * 3、DemoMessageReceiver 的 onReceivePassThroughMessage 方法用来接收服务器向客户端发送的透传消息。<br/>
 * 4、DemoMessageReceiver 的 onNotificationMessageClicked 方法用来接收服务器向客户端发送的通知消息，
 * 这个回调方法会在用户手动点击通知后触发。<br/>
 * 5、DemoMessageReceiver 的 onNotificationMessageArrived 方法用来接收服务器向客户端发送的通知消息，
 * 这个回调方法是在通知消息到达客户端时触发。另外应用在前台时不弹出通知的通知消息到达客户端也会触发这个回调函数。<br/>
 * 6、DemoMessageReceiver 的 onCommandResult 方法用来接收客户端向服务器发送命令后的响应结果。<br/>
 * 7、DemoMessageReceiver 的 onReceiveRegisterResult 方法用来接收客户端向服务器发送注册命令后的响应结果。<br/>
 * 8、以上这些方法运行在非 UI 线程中。
 *
 */
public class XMPushReceiver extends PushMessageReceiver {
    private String mRegId;
    private String mTopic;
    private String mAlias;
    private String mAccount;
    private String mStartTime;
    private String mEndTime;

    @Override
    public void onReceivePassThroughMessage(Context context, MiPushMessage message) {
        //接收服务器推送的透传消息，消息封装在 MiPushMessage类中
        AppSpPushLog.i("onReceivePassThroughMessage is called. " + message.toString());
        if (!TextUtils.isEmpty(message.getTopic())) {
            mTopic = message.getTopic();
        } else if (!TextUtils.isEmpty(message.getAlias())) {
            mAlias = message.getAlias();
        } else if (!TextUtils.isEmpty(message.getUserAccount())) {
            mAccount = message.getUserAccount();
        }
        JSONObject json = new JSONObject(message.getExtra());
        MessageUtil.onMessageArrived(context, message.getMessageId(), message.getTitle(), message.getContent(), json.toString());
    }

    @Override
    public void onNotificationMessageClicked(Context context, MiPushMessage message) {
        //接收服务器推送的通知消息，用户点击后触发，消息封装在 MiPushMessage类中
        AppSpPushLog.i("onNotificationMessageClicked is called. " + message.toString());

        if (!TextUtils.isEmpty(message.getTopic())) {
            mTopic = message.getTopic();
        } else if (!TextUtils.isEmpty(message.getAlias())) {
            mAlias = message.getAlias();
        } else if (!TextUtils.isEmpty(message.getUserAccount())) {
            mAccount = message.getUserAccount();
        }

        //todo 点击通知栏消息，发送广播给打开自定义页面
//        notificationMessageModel.setMessageType(3);
        SPUtil.put(context, "messsageId", message.getMessageId());
        JSONObject json = new JSONObject(message.getExtra());
        MessageUtil.onMessageClicked(context, message.getTitle(), message.getContent(), json.toString());
    }

    @Override
    public void onNotificationMessageArrived(Context context, MiPushMessage message) {
        //接收服务器推送的通知消息，消息到达客户端时触发，还可以接受应用在前台时不弹出通知的通知消息，消息封装在 MiPushMessage类中
        AppSpPushLog.i("onNotificationMessageArrived is called. " + message.toString());

        if (!TextUtils.isEmpty(message.getTopic())) {
            mTopic = message.getTopic();
        } else if (!TextUtils.isEmpty(message.getAlias())) {
            mAlias = message.getAlias();
        } else if (!TextUtils.isEmpty(message.getUserAccount())) {
            mAccount = message.getUserAccount();
        }
//        notificationMessageModel.setMessageType(3);
        JSONObject json = new JSONObject(message.getExtra());
        MessageUtil.onMessageArrived(context, message.getMessageId(), message.getTitle(), message.getContent(), json.toString());
    }

    @Override
    public void onCommandResult(Context context, MiPushCommandMessage message) {
        //获取给服务器发送命令的结果，结果封装在MiPushCommandMessage类中
        AppSpPushLog.i("onCommandResult is called. " + message.toString());
        String command = message.getCommand();
        List<String> arguments = message.getCommandArguments();
        String cmdArg1 = ((arguments != null && arguments.size() > 0) ? arguments.get(0) : null);
        String cmdArg2 = ((arguments != null && arguments.size() > 1) ? arguments.get(1) : null);
        if (MiPushClient.COMMAND_REGISTER.equals(command)) {
            if (message.getResultCode() == ErrorCode.SUCCESS) {
                mRegId = cmdArg1;
            }
        } else if (MiPushClient.COMMAND_SET_ALIAS.equals(command)) {
            if (message.getResultCode() == ErrorCode.SUCCESS) {
                mAlias = cmdArg1;
            }
        } else if (MiPushClient.COMMAND_UNSET_ALIAS.equals(command)) {
            if (message.getResultCode() == ErrorCode.SUCCESS) {
                mAlias = cmdArg1;
            }
        } else if (MiPushClient.COMMAND_SET_ACCOUNT.equals(command)) {
            if (message.getResultCode() == ErrorCode.SUCCESS) {
                mAccount = cmdArg1;
            }
        } else if (MiPushClient.COMMAND_UNSET_ACCOUNT.equals(command)) {
            if (message.getResultCode() == ErrorCode.SUCCESS) {
                mAccount = cmdArg1;
            }
        } else if (MiPushClient.COMMAND_SUBSCRIBE_TOPIC.equals(command)) {
            if (message.getResultCode() == ErrorCode.SUCCESS) {
                mTopic = cmdArg1;
            }
        } else if (MiPushClient.COMMAND_UNSUBSCRIBE_TOPIC.equals(command)) {
            if (message.getResultCode() == ErrorCode.SUCCESS) {
                mTopic = cmdArg1;
            }
        } else if (MiPushClient.COMMAND_SET_ACCEPT_TIME.equals(command)) {
            if (message.getResultCode() == ErrorCode.SUCCESS) {
                mStartTime = cmdArg1;
                mEndTime = cmdArg2;
            }
        }
    }

    @Override
    public void onReceiveRegisterResult(Context context, MiPushCommandMessage message) {
        //获取给服务器发送注册命令的结果，结果封装在MiPushCommandMessage类中
        AppSpPushLog.i("onReceiveRegisterResult is called. " + message.toString());
        String command = message.getCommand();
        List<String> arguments = message.getCommandArguments();
        String cmdArg1 = ((arguments != null && arguments.size() > 0) ? arguments.get(0) : null);
        String cmdArg2 = ((arguments != null && arguments.size() > 1) ? arguments.get(1) : null);
        if (MiPushClient.COMMAND_REGISTER.equals(command)) {
            if (message.getResultCode() == ErrorCode.SUCCESS) {
                mRegId = cmdArg1;
                //收到regId之后,可以设置alias、userAccount、topic，将数据传给服务器
                AppSpPushConstant.pushToken = mRegId;
                AppSpPushConfig.getInstance().sendRegTokenToServer(new IAppSpCallback() {
                    @Override
                    public void pushInfo(AppSpModel<String> appSpModel) {

                    }

                    @Override
                    public void error(String code, String msg) {

                    }
                });
            }
        }

    }
}
